package cn.edu.wzut;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.FileWriter;
import java.io.IOException;

@Controller
public class RegisterController {

    @RequestMapping("/register")
    public String showRegister(Model model) {
        model.addAttribute("registerBean", new RegisterBean());
        return "register.html";
    }

    @RequestMapping(value = "/doRegister", method = RequestMethod.POST)
    public String doRegister(RegisterBean registerBean, Model model) {
        // 验证用户名长度大于3
        if (registerBean.getUserName().length() <= 3) {
            model.addAttribute("errorMessage", "用户名长度必须大于3");
            return "register.html";
        }

        // 验证两次密码输入是否相同
        if (!registerBean.getPassword().equals(registerBean.getConfirmPassword())) {
            model.addAttribute("errorMessage", "两次密码输入不一致");
            return "register.html";
        }

        // 将用户名密码保存到文本文件
        try {
            FileWriter writer = new FileWriter("user_credentials.txt", true);
            writer.write("用户名: " + registerBean.getUserName() + ", 密码: " + registerBean.getPassword() + "\n");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
            model.addAttribute("errorMessage", "保存用户信息时发生错误");
            return "register.html";
        }

        return "redirect:/login"; // 重定向到登录页面
    }

}
